import frappe
from frappe.model.mapper import get_mapped_doc
from erpnext.stock.doctype.material_request.material_request import set_missing_values

@frappe.whitelist()
def get_party_advance_account_backup(party_type, party, company=None):
	"""Returns the account for the given `party`.
		Will first search in party (Customer / Supplier) record, if not found,
		will search in group (Customer Group / Supplier Group),
		finally will return default."""
	if not company:
		frappe.throw(_("Please select a Company"))

	if not party:
		return

	fieldname = "default_advance_accounts_receivable" if party_type=="Customer" else "default_advance_accounts_payable"
	account = frappe.db.get_value("Party Account",
		{"parenttype": party_type, "parent": party, "company": company},  fieldname)

	# if not account and party_type in ['Customer', 'Supplier']:
	# 	party_group_doctype = "Customer Group" if party_type=="Customer" else "Supplier Group"
	# 	group = frappe.get_cached_value(party_type, party, scrub(party_group_doctype))
	# 	account = frappe.db.get_value("Party Account",
	# 		{"parenttype": party_group_doctype, "parent": group, "company": company}, "account")

	if not account and party_type in ['Customer', 'Supplier']:
		account = frappe.get_cached_value('Company',  company,  fieldname)

	return account

@frappe.whitelist()
def get_advance_payment_info_backup(reference_doctype, reference_name, outstanding):
	payment_amount = outstanding
	doc = frappe.get_doc(reference_doctype, reference_name)
	if reference_doctype == 'Sales Order':
		party_type = 'Customer'
		party = doc.customer
	else:
		party_type = 'Supplier'
		party = doc.supplier
	account = get_party_advance_account(party_type, party, doc.company)   
	payment_term = doc.payment_schedule and doc.payment_schedule[0] or None
	if not doc.advance_paid and payment_term and payment_term.is_advance:
		payment_amount = payment_term.payment_amount
	return (account, payment_amount) 

@frappe.whitelist()
def make_supplier_quotation(source_name, target_doc=None):
	def postprocess(source, target_doc):
		target_doc.supplier = supplier
		set_missing_values(source, target_doc)

	mr = frappe.get_doc('Material Request', source_name)
	item_default_list = frappe.get_all('Item Default', 
									filters = {'company': mr.company,
											'parent':('in', [m.item_code for m in mr.items])},
									fields=['default_supplier','parent'])
	supplier_item_map = {}
	for item_default in item_default_list:
		item_list = supplier_item_map.setdefault(item_default.default_supplier, [])
		item_list.append(item_default.parent)

	doclist = []
	for (supplier, item_list) in supplier_item_map.items():
		if not supplier: continue
		doc = get_mapped_doc("Material Request", source_name, {
			"Material Request": {
				"doctype": "Supplier Quotation",
				"validation": {
					"docstatus": ["=", 1],
					"material_request_type": ["=", "Purchase"]
				}
			},
			"Material Request Item": {
				"doctype": "Supplier Quotation Item",
				"field_map": {
					"name": "material_request_item",
					"parent": "material_request",
					"sales_order": "sales_order"
				},
				"condition": lambda doc: doc.item_code in item_list
			}
		}, target_doc, postprocess)

		doclist.append(doc)

	return doclist	   